import React, { Component, Fragment } from 'react';
import StandardTable from '@/components/StandardTable';
import { Card, Form, Input, Select, DatePicker, Button, Modal, Alert, Badge } from 'antd';
import { connect } from 'dva';
import styles from './VerificationList.less';
import Media from 'react-media';
import ManageList from '@/components/ManageList';
import SelectForm from '@/components/SelectForm';
import VerificationDetail from './VerificationDetail';
import moment from 'moment';
import router from 'umi/router';
import AdSearch from '@/components/AdSearch';
import RightDraw from '@/components/RightDraw';
import SearchSelect from '@/components/SearchSelect';
import { columns1, columnsBillNo } from '@/pages/Common/common';
import AdSelect from '@/components/AdSelect';
import FileReader from '@/components/FileReader';
import { billStateList, billStateOnlyReadList, allDictList } from '@/utils/constans';
import { vitifyCheck, formateDateToMin, queryDict } from '@/utils/common';
import AntdFormItem from '@/components/AntdFormItem';
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';
import AdButton from '@/components/AdButton';
import FileImport from '@/components/FileImport';
import { codes, allDispatchType, renderTableAdSelect } from './utils';
const FormItem = Form.Item;
const { Option } = Select;
const { confirm } = Modal;

@ManageList
@connect(({ verification, component, loading, common }) => ({
  verification,
  loading: loading.models.verification,
  ownCompany: common.ownCompany,
  dictObject: component.dictObject,
  searchValue: component.searchValue,
}))
@Form.create()
class VerificationList extends Component {
  state = {
    visible: false,
    id: '',
    formValues: {},
    cars: [],
    billNos: [],
    expandForm: false,
    selectedRows: [],
    isBillStatus: '',
    visibleFile: false,
  };
  className = 'VerificationList';
  componentWillMount() {
    const allDict = [allDictList.inspectionType, allDictList.currencyType];
    queryDict({ props: this.props, allDict });
  }
  columns = [
    {
      title: '单据号',
      dataIndex: 'annualNo',
      render: (text, record) => (
        <AdButton
          mode="a"
          onClick={e => this.showDetail(e, record.id, record)}
          text={text}
          code={codes.showDetail}
        />
      ),
      fixed: this.props.isMobile ? false : true,
    },
    {
      title: '状态',
      dataIndex: 'billStatus',
      render: (text, record) => (
        <AdSelect
          onlyRead={true}
          value={text ? text : record.status}
          data={billStateOnlyReadList}
        />
      ),
      width: 100,
    },
    {
      title: '主车牌',
      dataIndex: 'cartPlateNo',
    },
    {
      title: '所属公司',
      dataIndex: 'ownCompanyName',
      render: text => <span title={text}>{text}</span>,
      width: 250,
    },
    {
      title: '类型',
      dataIndex: 'annualAuditType',
      render: text =>
        renderTableAdSelect({ props: this.props, value: text, key: allDictList.inspectionType }),
    },
    {
      title: '有效期',
      dataIndex: 'expiryTime',
      render: (text, record) => <span>{`${record.expiryStartTime}~${record.expiryEndTime}`}</span>,
      width: 200,
    },
    {
      title: '附件',
      dataIndex: 'attaQuantity',
      width: 80,
      render: (text, record) =>
        text &&
        Number(text) > 0 && (
          <Badge className="cus_badge" count={text}>
            <div className="head-example">
              <FileReader
                type="list"
                count={text}
                urlType="tms"
                params={{ bizId: record.id, fileBizType: 'YEARAUDIT_MANA' }}
              />
            </div>
          </Badge>
        ),
    },
    {
      title: '费用',
      dataIndex: 'feeCost',
      render: text => {
        return <span>{text && Number(text) !== 0 ? Number(text).toFixed(2) : 0}</span>;
      },
    },
    {
      title: '币种',
      dataIndex: 'currencyType',
      render: text =>
        renderTableAdSelect({
          props: this.props,
          value: text,
          key: allDictList.currencyType,
        }),
      width: 100,
    },
    {
      title: '年审时间',
      dataIndex: 'yearAuditTime',
    },
    {
      title: '证件号码',
      dataIndex: 'cardCode',
    },
    {
      title: '账单号',
      dataIndex: 'billNo',
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      render: text => (
        <AdSearch
          label="loginName"
          name="sysName"
          value={this.props.searchValue[text]}
          onlyRead={true}
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
    },
    {
      title: '更新人',
      dataIndex: 'updateBy',
      render: text => (
        <AdSearch
          label="loginName"
          name="sysName"
          value={this.props.searchValue[text]}
          onlyRead={true}
        />
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    this.query();
  }

  query = params => {
    const { dispatch, searchValue } = this.props;
    dispatch({
      type: 'verification/verificationList',
      payload: params || {},
      callback: data => {
        let valueList = [];
        data.map(v => {
          if (!data) return;
          const labels = ['updateBy', 'createBy'];
          labels.map(item => {
            if (v[item] && !valueList.includes(v[item])) {
              valueList.push(v[item]);
              !searchValue[v[item]] &&
                dispatch({
                  type: 'component/querySearchValue',
                  payload: {
                    params: { loginName: v[item] },
                    url: 'tms/tms-annual-audit/selectUser_s',
                  },
                });
            }
          });
        });
      },
    });
  };
  handleStandardTableChange = param => {
    const { formValues } = this.state;
    const params = {
      ...formValues,
      ...param,
    };
    this.query(params);
  };

  // 重置条件查询表单
  handleFormReset = () => {
    const { dispatch } = this.props;
    this.setState({ formValues: {}, cars: [], billNos: [] });
    this.query();
  };

  toggleForm = expandForm => {
    this.setState({
      expandForm,
    });
  };

  // 执行条件查询表单
  handleSearch = values => {
    const { dispatch } = this.props;
    const { yearAuditTime, expiryTime, ...value } = values;
    const { cars, billNos } = this.state;
    if (cars.length > 0) {
      const vehicleId = cars.map(v => {
        return v.id;
      });
      value.vehicleId = vehicleId.join(',');
    } else {
      value.vehicleId = '';
    }
    if (billNos.length > 0) {
      const billId = billNos.map(v => {
        return v.id;
      });
      value.billId = billId.join(',');
    } else {
      value.billId = '';
    }
    if (expiryTime) {
      value.expiryStartTime = moment(expiryTime[0]).format(dateFormat);
      value.expiryEndTime = moment(expiryTime[1]).format(dateFormat);
    }
    if (yearAuditTime) {
      value.yearAuditStartTime = moment(yearAuditTime[0]).format(dateFormat);
      value.yearAuditEndTime = moment(yearAuditTime[1]).format(dateFormat);
    }
    this.setState({
      formValues: value,
    });

    this.query(value);
  };

  handleAdd = () => {
    const { dispatch } = this.props;
    router.push('/carDaily/verificationList/addVerification');
  };

  handleEdit = () => {
    const { id } = this.state;

    this.closeDetail();
    router.push(`/carDaily/verificationList/editVerification/${id}`);
  };

  // 关闭右抽屉
  closeDetail = () => {
    this.setState({
      visible: false,
    });
  };
  // 打开右抽屉
  showDetail = (e, id, record) => {
    e.stopPropagation();
    const { dispatch } = this.props;
    const status = record.billStatus ? record.billStatus : record.status;
    const isBillStatus = status === 'CONFIRM' || status === 'WAIT';
    this.setState({
      visible: true,
      id,
      isBillStatus,
    });
    // 查询详情
    dispatch({
      type: 'verification/verificationDetail',
      payload: { id },
    });
  };
  getValue = (values, type) => {
    this.setState({
      [type]: values,
    });
  };

  // 删除
  delPaper = () => {
    const { dispatch } = this.props;
    const { id, formValues } = this.state;
    const _this = this;
    confirm({
      title: '确定删除这条数据吗？',
      content: ' ',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: allDispatchType.delete,
          payload: { id },
          callback: () => {
            _this.closeDetail();
            _this.query({
              ...formValues,
            });
          },
        });
      },
    });
  };
  /**
   * 生成账单
   */
  generatedBills = () => {
    const { dispatch } = this.props;
    const { selectedRows, formValues } = this.state;
    const checkBill = this.checkBill();
    if (!checkBill) return;
    dispatch({
      type: 'verification/generatedBills',
      payload: { ids: selectedRows.map(v => v.id) },
      callback: data => {
        if (!data) return;
        this.setState({
          selectedRows: [],
        });
        this.query(formValues);
        //跳转到账单的编辑页面
        router.push(`/carAccount/billList/editBill/${data}`);
      },
    });
  };

  /**
   * 生成账单校验 状态已提交，同一公司，同一加油方式
   */

  checkBill = () => {
    const { selectedRows } = this.state;
    const ownCompanyName = vitifyCheck({
      selectedRows,
      key: 'ownCompanyName',
      warn: '所选记录必须所属公司相同！',
    });
    if (!ownCompanyName) return false;
    return true;
  };
  handleSelectRows = selectedRows => {
    this.setState({
      selectedRows,
    });
  };

  //导入：
  handleImportFile = () => {
    const { visibleFile } = this.state;
    this.setState({ visibleFile: !visibleFile });
  };

  selectAll = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'verification/selectAll',
      payload: formValues,
      callback: data => {
        this.setState({
          selectedRows: [],
        });
        if (!data) return;

        this.query(formValues);
        //跳转到账单的编辑页面
        router.push(`/carAccount/billList/editBill/${data}`);
      },
    });
  };
  render() {
    const {
      form,
      loading,
      verification: { verificationList, carList },
      isMobile,
      ownCompany,
      dictObject,
    } = this.props;

    const {
      id,
      expandForm,
      isBillStatus,
      formValues,
      selectedRows,
      visible,
      visibleFile,
    } = this.state;

    const { getFieldDecorator } = form;
    const commonParams = {
      getFieldDecorator,
    };
    // firstForm 参数
    const firstFormItem = (
      <FormItem label="单据号">
        {getFieldDecorator('invoiceNo')(<Input placeholder="请输入" />)}
      </FormItem>
    );
    const secondFormItem = (
      <AntdFormItem label="状态" code="billStatus" {...commonParams}>
        <AdSelect data={billStateList} isExist={true} mode="multiple" />
      </AntdFormItem>
    );
    // secondForm 参数
    const otherFormItem = [
      [
        <FormItem label="年审时间">
          {getFieldDecorator('yearAuditTime')(<RangePicker style={{ width: '100%' }} />)}
        </FormItem>,
      ],
      [
        <FormItem label="车牌号">
          {getFieldDecorator('vehicleId')(
            <SearchSelect
              dataUrl="tms/tms-annual-audit/selectVehicle"
              url="tms/tms-annual-audit/selectVehicleView_s" // selectedData只只有id时需要传url
              selectedData={this.state.cars} // 选中值
              multiple={false} // 是否多选
              showValue="cartPlateOneNo"
              searchName="cartPlate"
              columns={columns1} // 表格展示列
              onChange={values => this.getValue(values, 'cars')} // 获取选中值
              scrollX={480}
              id="verification_1"
              allowClear={true}
            />
          )}
        </FormItem>,
        <FormItem label="所属公司">
          {getFieldDecorator('mdsCompanyId')(
            <Select
              showSearch
              allowClear={true}
              filterOption={(input, option) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
              placeholder="请选择"
              style={{ width: '100%' }}
            >
              <Option value="请选择">请选择</Option>
              {ownCompany.map((v, i) => {
                return (
                  <Option key={i} value={v.customerCode}>
                    {v.customerName}
                  </Option>
                );
              })}
            </Select>
          )}
        </FormItem>,
        <AntdFormItem label="类型" code="annualAuditType" {...commonParams}>
          <AdSelect isExist={true} data={dictObject[allDictList.inspectionType]} />
        </AntdFormItem>,
      ],
      [
        <FormItem label="有效期">
          {getFieldDecorator('expiryTime')(<RangePicker style={{ width: '100%' }} />)}
        </FormItem>,
        <FormItem label="账单号">
          {getFieldDecorator('billId')(
            <SearchSelect
              dataUrl="tms/tms-annual-audit/selectTmsBillList_s"
              selectedData={this.state.billNos} // 选中值
              multiple={false} // 是否多选
              showValue="billNo"
              searchName="billNo"
              columns={columnsBillNo} // 表格展示列
              onChange={values => this.getValue(values, 'billNos')} // 获取选中值
              scrollX={200}
              id="verification_2"
              allowClear={true}
              payload={{ type: 'ANNUALAUDIT' }}
            />
          )}
        </FormItem>,
        'operatorButtons',
      ],
    ];

    const selectFormParams = {
      firstFormItem,
      secondFormItem,
      otherFormItem,
      form,
      code: codes.select,
      className: this.className,
      handleFormReset: this.handleFormReset,
      handleSearch: this.handleSearch,
      toggleForm: this.toggleForm,
    };

    const header = (
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14 }}>
        <h2>年审详情</h2>
        <div>
          <Button.Group>
            <AdButton
              onClick={() => this.delPaper()}
              disabled={!isBillStatus}
              text="删除"
              code={codes.delete}
              type="danger"
            />
            <AdButton
              disabled={!isBillStatus}
              onClick={this.handleEdit}
              text="编辑"
              type="primary"
              code={codes.edit}
            />
          </Button.Group>
          <AdButton
            style={{ marginLeft: 8 }}
            onClick={this.closeDetail}
            text="关闭"
            code={codes.showDetail}
          />
        </div>
      </div>
    );

    const billStatus = formValues.billStatus;
    const disabledRowSelected =
      billStatus && billStatus.length === 1 && billStatus.includes('CONFIRM') ? false : true;

    const rightDrawParams = {
      isMobile,
      visible,
      title: '年审详情',
      code: codes.showDetail,
      closeDetail: this.closeDetail,
      buttons: (
        <span>
          <AdButton
            onClick={() => this.delPaper()}
            disabled={!isBillStatus}
            text="删除"
            ghost
            code={codes.delete}
            type="danger"
          />
          <AdButton
            disabled={!isBillStatus}
            onClick={this.handleEdit}
            text="编辑"
            style={{ marginLeft: 8 }}
            type="primary"
            code={codes.edit}
          />
        </span>
      ),
    };
    return (
      <Fragment>
        <FileImport
          visibleFile={visibleFile}
          handleCancel={() => {
            this.handleImportFile();
          }}
          urlImport={`tms/tms-annual-audit/importInspection`} //导入地址
          // urlQuery={[{ url: `tms/tms-annual-audit/selectList`, payload: {} }]}
          queryData={[this.query]}
          urlCase={`attachment/年审导入模板.xlsx`}
          accept=".xls,.xlsx"
        />
        <div className={styles.tableListForm}>
          <SelectForm {...selectFormParams} />
          <div className={styles.tableListOperator}>
            <div style={{ display: 'flex' }}>
              {selectedRows.length > 0 && (
                <Alert
                  message={
                    <Fragment>
                      已选择
                      <a style={{ fontWeight: 600 }}>{selectedRows.length}</a> 项&nbsp;&nbsp;
                      <span style={{ marginLeft: 8 }}>
                        总计&nbsp;
                        <span style={{ fontWeight: 600 }}>
                          {verificationList.pagination && verificationList.pagination.total}
                        </span>
                      </span>
                      <AdButton
                        code={codes.bill}
                        mode="a"
                        text="选择全部生成账单"
                        onClick={this.selectAll}
                        style={{ marginLeft: 24 }}
                      ></AdButton>
                    </Fragment>
                  }
                  type="info"
                  showIcon
                />
              )}
              <Button.Group>
                <AdButton onClick={() => this.handleImportFile()} text="导入" code={codes.import} />
                <AdButton
                  disabled={!selectedRows.length > 0}
                  onClick={() => this.generatedBills()}
                  text={`生成账单${selectedRows.length > 0 ? '(' + selectedRows.length + ')' : ''}`}
                  code={codes.bill}
                />
              </Button.Group>
            </div>

            <AdButton type="primary" onClick={this.handleAdd} text="新建" code={codes.add} />
          </div>
          <StandardTable
            selectedRows={selectedRows}
            disabledSelectedRows={{ code: ['billStatus', 'status'], value: ['CONFIRM', 'WAIT'] }}
            getCheckboxProps={record => {
              const status = record.billStatus ? record.billStatus : record.status;
              const checked = status === 'CONFIRM' || status === 'WAIT';
              return !checked;
            }}
            loading={loading}
            onSelectRow={this.handleSelectRows}
            data={verificationList}
            columns={this.columns}
            onPaginationChange={this.handleStandardTableChange}
            expandForm={expandForm}
            className={this.className}
            code={codes.page}
          />
        </div>
        <RightDraw {...rightDrawParams}>
          <VerificationDetail isMobile={isMobile} id={id} />

          {/* <VerificationDetail id={id} /> */}
        </RightDraw>
      </Fragment>
    );
  }
}
export default VerificationList;
